package com.yb.livewykt.util

import android.graphics.Bitmap
import android.graphics.Matrix
import android.media.ExifInterface
import java.io.IOException
import java.nio.ByteBuffer

/**
 * 旋转 Bitmap
 *
 * @param bitmap
 * @param orientation
 * @return
 */
fun rotateBitmap(bitmap: Bitmap, orientation: Int): Bitmap {
    var bitmap = bitmap
    if (orientation == 90 || orientation == 180 || orientation == 270) {
        val matrix = Matrix()
        matrix.postRotate(orientation.toFloat())
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
    }
    return bitmap
}

/**
 * 获取图片的方向
 *
 * @param path
 * @return
 */
fun getPhotoOrientation(path: String): Int {
    var orientation = 0
    var tagOrientation = 0
    try {
        tagOrientation = ExifInterface(path).getAttributeInt(ExifInterface.TAG_ORIENTATION, -1)
    } catch (e: IOException) {
    }
    if (tagOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
        orientation = 90
    } else if (tagOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
        orientation = 180
    } else if (tagOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
        orientation = 270
    }
    return orientation
}

/**
 * 获取 Bitmap 的 RGBA 字节数组
 *
 * @param bitmap
 * @return
 */
fun copyRgbaByteFromBitmap(bitmap: Bitmap): ByteArray {
    val bytes = ByteArray(bitmap.byteCount)
    val rgbaBuffer = ByteBuffer.wrap(bytes)
    bitmap.copyPixelsToBuffer(rgbaBuffer)
    return bytes
}
